package com.itheima.controller;


import com.github.pagehelper.Page;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.entity.SmallPageBean;
import com.itheima.exception.CheckItemDeleteFailException;
import com.itheima.pojo.CheckItem;
import com.itheima.service.CheckItemService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/checkitem")
public class CheckItemController {
    //注入checkItemService
    //查找服务
    @Reference
    private CheckItemService checkItemService;

    //添加数据 -- add
    @RequestMapping("/add")
    public Result add(@RequestBody CheckItem checkItem){
        System.out.println(checkItem);
        try {
            checkItemService.add(checkItem);
        }catch (Exception e){
            e.printStackTrace();
            //服务调用失败
            return new Result(false, MessageConstant.ADD_CHECKITEM_FAIL);
        }
        return new Result(true, MessageConstant.ADD_CHECKITEM_SUCCESS);
    }

    //分页查询 -- findPage -- 调用service层的pageQuery(根据条件查询) -- 调用dao层方法selectByCondition(queryString) 动态执行sql
    //条件不为空 就执行模糊查询（因为有可能输关键字）
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        //调用方法
        return checkItemService.pageQuery(queryPageBean);
    }

    @RequestMapping("/edit")
    public Result edit(@RequestBody CheckItem checkItem){
        //调用方法
        try {
            checkItemService.edit(checkItem);
        }catch(Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.EDIT_CHECKITEM_FAIL);

        }
        return new Result(true,MessageConstant.EDIT_CHECKITEM_SUCCESS);
    }
    //删除检查项
    //@PreAuthorize("hasAuthority('CHECKITEM_DELETE')")//权限校验
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @RequestMapping("/delete")
    public Result delete(Integer id){
        //调用方法
        try {
            checkItemService.deleteById(id);
        }catch(Exception e){
            e.printStackTrace();
            if (e instanceof CheckItemDeleteFailException){
                return new Result(false,"已经有检查组关联此检查项, 请优先删除检查组后再操作");
            }
            return new Result(false,MessageConstant.DELETE_CHECKITEM_FAIL);
        }
        return new Result(true,MessageConstant.DELETE_CHECKITEM_SUCCESS);
    }

    @RequestMapping("/findAll")
    public PageResult findAll(String checkGroupId,@RequestBody SmallPageBean smallPageBean){
        return  checkItemService.findAll(checkGroupId,smallPageBean);
    }
}
